package com.qianxp.authorize.interceptor;

import com.qianxp.authorize.annotation.Permission;
import com.qianxp.authorize.entity.PermissionCode;
import com.qianxp.authorize.exception.AuthorizeException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**@author qianxiaopeng
 * 鉴权类，AOP实现
 */
@Aspect
@Component
public class AuthInterceptor {
    private static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    /**
     *  切入点为Permission标记的类
     */
    @Around(value = "@annotation(com.qianxp.authorize.annotation.Permission)")
    public void authirized(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        logger.info("鉴权方法执行。。");
        Signature signature = proceedingJoinPoint.getSignature();
        Method realMethod = proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(signature.getName(), ((MethodSignature) signature).getMethod().getParameterTypes());
        Permission permission = realMethod.getAnnotation(Permission.class);
        if (PermissionCode.EXCULEDE.value().equals(permission.value())) {
            proceedingJoinPoint.proceed();
        }else if(PermissionCode.PERMISSION.value().equals(permission.value())){
            // do something
        }
        throw new AuthorizeException("非法访问！您没有访问此方法的权限，请联系管理员。");

    }
}
